
import shoppingcarinfosModel from "../model/shoppingcarinfosModel"
export default {
    namespaced: true,
    state: {
        list: [],
        totalnum: null
    },
    getters: {
        price(state) {
            let selectlist = state.list.filter(item => item.ischecked)
            console.log(selectlist)
            if (selectlist.length) {
                return selectlist.map(item => item.goodsprice * item.goodsbuynum).reduce((a, b) => a + b)
            } else {
                return 0
            }

        },
        selectnum(state) {
            let selectlist = state.list.filter(item => item.ischecked)
            console.log(selectlist)
            if (selectlist.length) {
                return selectlist.map(item => item.goodsbuynum).reduce((a, b) => a + b)
            } else {
                return 0
            }
        }
    },
    mutations: {
        getchangeall(state, playload) {
            state.list.forEach(item => item.ischecked = playload)
        },
        innittotalnum(state) {
            state.totalnum = state.list.length
        },
        innitlist(state, playload) {
            state.list = playload
        },
        dellist(state, playload) {
            state.list = state.list.filter(item => item.id != playload)
        },
        asynccalc(state, playload) {
            state.list = state.list.map(item => {
                if (item.id == playload.id) {
                    item.goodsbuynum = item.goodsbuynum * 1 + playload.num * 1
                }
                return item
            })
        }
    },
    actions: {
        async innitlist(context, playload) {
            console.log(playload)
            let { data: list } = await shoppingcarinfosModel.query({
                userid: playload
            })
            context.commit("innitlist", list.map(item => {
                item.ischecked = false
                return item
            })),
                context.commit("innittotalnum")
        },

        async dellist(context, playload) {
            await shoppingcarinfosModel.del(playload)
            context.commit("dellist", playload)
        },
        async asynccalc(context, playload) {
            await shoppingcarinfosModel.updata(playload.id, {
                goodsbuynum: playload.goodsbuynum * 1 + playload.num * 1
            })

            context.commit("asynccalc", playload)
        }

    }
}